package hdeirls

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"read-hub/cache"
	"read-hub/models"
	"read-hub/pkg"
	"time"
)

func Dl(c *gin.Context) {
	name := c.PostForm("name")
	passes := c.PostForm("passes")

	if name == "" || passes == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	redis_key := "redis_dl" + name
	po, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if po >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次,禁止登录",
		})
		return
	}
	var user models.User
	err := models.DB.Where("name=?", name).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户查询失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Passes != pkg.Md5(passes) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if po == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "错误3次封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "登录成功",
		"data": user,
	})
	return
}
func Xq(c *gin.Context) {
	id := c.Query("id")

	var are models.Ares

	redid_key := "redis_id" + id
	po, _ := cache.Rdb.Get(cache.Ctx, redid_key).Result()
	if po == "" {
		models.DB.Where("id=?", id).First(&are)
		JsonXq, _ := json.Marshal(are)
		cache.Rdb.Set(cache.Ctx, redid_key, JsonXq, time.Hour*2)
	} else {
		json.Unmarshal([]byte(po), &are)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": are,
	})
	return
}
func List(c *gin.Context) {
	var user []models.Ares
	redid_key := "redis_list"
	po, _ := cache.Rdb.Get(cache.Ctx, redid_key).Result()
	if po == "" {
		models.DB.Find(&user)
		JsonXq, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, redid_key, JsonXq, time.Hour*2)
	} else {
		json.Unmarshal([]byte(po), &user)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": user,
	})
	return
}
func Add(c *gin.Context) {

}
